package com.zoro.dyformservice.support.jpa;

import com.zoro.dyformservice.interfaces.CodeData;
import com.zoro.dyformservice.utils.StringUtils;
import jakarta.persistence.AttributeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;

/**
 * @author zhaoxingwu
 */
public class AbstractCodeDataConverter<T extends CodeData> implements AttributeConverter<T, String> {

    private final static Logger LOGGER = LoggerFactory.getLogger(AbstractCodeDataConverter.class);
    private final T[] items;

    public AbstractCodeDataConverter(Class<T> tClass) throws IllegalAccessException {
        if (tClass == null) {
            throw new NullPointerException("class can not be null for attribute converter");
        }
        if (!tClass.isEnum()) {
            throw new IllegalAccessException(String.format("class : %s is not a enum!", tClass.getName()));
        }
        this.items = tClass.getEnumConstants();
        LOGGER.debug("load attribute converter for Class: {}", tClass.getName());
    }

    @Override
    public String convertToDatabaseColumn(T attribute) {
        if (attribute == null) {
            return null;
        }
        return attribute.getCode();
    }

    @Override
    public T convertToEntityAttribute(String dbData) {
        // TODO 这个 做不到完全自动化， 不开发呀~， 因为不能在运行时等到具体的类型，转不了
        if (this.items == null) {
            return null;
        }
        return Arrays.stream(this.items).filter(v -> StringUtils.equal(dbData, v.getCode())).findFirst().orElse(null);
    }
}
